
<template>
  <div>
    <el-cascader
      ref="areaCascade"
      :value="value.code"
      :options="areaData"
      :props="props"
      collapse-tags
      clearable
      separator=" "
      @change="handleChange"
    />
  </div>
</template>
<script>
const areaList = require('./area')
import _ from 'lodash'
export default {
  props: {
    value: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      areaData: areaList,
      props: {
        multiple: false, // 是否多选
        label: 'name',
        value: 'code',
        children: 'children'
      }
    }
  },
  watch: {
    // 数据回显
    value: {
      immediate: true,
      handler(val) {
        console.log(val)
        const { province, city, country } = val
        val.code = []
        val.code.push(province)
        if (city !== '')val.code.push(city)
        if (country !== '')val.code.push(country)
        return val
      }
    }
  },
  created() {
  },
  methods: {
    // 初始化省市区数据
    handleChange(value) {
      const _value = _.cloneDeep(value) // 数据深克隆  避免回显问题
      if (_value.length !== 0) {
        const result = {
          address: this.$refs.areaCascade.getCheckedNodes()[0].pathLabels.join(''),
          province: _value[0],
          city: _value[1] !== undefined ? _value[1] : '',
          country: _value[2] !== undefined ? _value[2] : ''
        }
        this.$emit('input', result)
      }
    }
  }
}
</script>
